package com.taomeng.shiro.realms;

import com.taomeng.entity.Permission;
import com.taomeng.entity.Role;
import com.taomeng.entity.Student;
import com.taomeng.entity.User;
import com.taomeng.service.IPermissionService;
import com.taomeng.service.IUserService;
import com.taomeng.service.RoleService;
import com.taomeng.service.StudentService;
import com.taomeng.util.Md5Util;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class CrmRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private StudentService studentService;

    //获取权限信息,以便框架判断资源是否拥有权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取当前用户
        if (principals.getPrimaryPrincipal() instanceof Student){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //添加请假的权限
            info.addStringPermission("leave:student");
            return info;
        }
        User loginUser = (User) principals.getPrimaryPrincipal();

        //通过当前用户获取用户的角色
        List<Role> roles = roleService.findRolesByLoginUserId(loginUser.getId());


        //通过角色获取用户拥有的权限
        Set<Permission> userPermissions = permissionService.findUserPermissionsByUserRoles(roles);
        //把用户权限返回shiro框架
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给当前用户赋予角色
        for (Role role : roles) {
            info.addRole(role.getSn());
        }
        //有一个Permission就要给框架返回一个
        for (Permission permission : userPermissions) {
            if (permission != null) {
                info.addStringPermission(permission.getSn());
            }
        }

        return info;
    }


    //获取用户身份信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //把token转换为UsernamePasswordToken
        UsernamePasswordToken upt = (UsernamePasswordToken) token;
        Object principal = null;
        Object hashedCredentials = null;

        //获取用户名
        String username = upt.getUsername();
        if (username.trim().length() == 9) {   //学生用户
            Student student = studentService.findByStudentNum(username);
            if (student == null) throw new UnknownAccountException();
            //身份信息返回给框架，让框架做比对
            principal = student;//身份不仅可以是用户名，还可以是整个用户
            hashedCredentials = student.getPassword();//必须保证数据库里面的密码是加密加盐
        } else {
            //根据用户名获取用户
            User user = userService.findByUsername(username);
            //做逻辑判断
            if (user == null) {
                throw new UnknownAccountException();
            }
            //身份信息返回给框架，让框架做比对
            principal = user;//身份不仅可以是用户名，还可以是整个用户
            hashedCredentials = user.getPassword();//必须保证数据库里面的密码是加密加盐
        }
        ByteSource credentialsSalt = ByteSource.Util.bytes(Md5Util.SALT);
        return new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, getName());
    }


}
